

package top.continew.admin.question.user.service.question.entity;

import com.alibaba.fastjson2.JSON;
import lombok.Data;
import top.continew.admin.question.model.question.Question;
import top.continew.admin.question.user.service.question.enums.ProblemStateEnum;
import top.continew.admin.question.user.service.question.enums.QuestionTypeEnum;

import java.util.List;

@Data
public class FillInTheBlankQuestion extends AbstractQuestion {

    // 空格数
    private Long blankSum;

    public void init(Question question) {
        super.init(question);
        blankSum = question.getBlankSum();
    }

    @Override
    public CorrectResult correct(String userAnswer) {
        CorrectResult correctResult = new CorrectResult();
        correctResult.setCorrectAnswer(answer);
        correctResult.setUserAnswer(userAnswer);
        correctResult.setProblemState(ProblemStateEnum.UNCHECK.getCode());

        if (userAnswer == null || userAnswer.trim().isEmpty()) {
            return correctResult;
        }

        try {
            // 预处理用户答案：去除多余空格，统一小写
            String[] userAnswerList = userAnswer.split(",");
            for (int i = 0; i < userAnswerList.length; i++) {
                userAnswerList[i] = userAnswerList[i].trim().toLowerCase();
            }

            // 检查答案数量是否匹配
            if (blankSum != userAnswerList.length) {
                correctResult.setProblemState(ProblemStateEnum.WRONG.getCode());
                return correctResult;
            }

            // 预处理标准答案
            List<String> answerList = JSON.parseArray(answer, String.class);
            answerList.replaceAll(s -> s.trim().toLowerCase());

            // 判断用户答案是否正确
            for (int i = 0; i < userAnswerList.length; i++) {
                // 支持多个正确答案，用|分隔
                String[] possibleAnswers = answerList.get(i).split("\\|");
                boolean isCorrect = false;
                for (String possibleAnswer : possibleAnswers) {
                    if (userAnswerList[i].equals(possibleAnswer.trim())) {
                        isCorrect = true;
                        break;
                    }
                }
                if (!isCorrect) {
                    correctResult.setProblemState(ProblemStateEnum.WRONG.getCode());
                    return correctResult;
                }
            }
            correctResult.setProblemState(ProblemStateEnum.RIGHT.getCode());
        } catch (Exception e) {
            correctResult.setProblemState(ProblemStateEnum.WRONG.getCode());
        }
        return correctResult;
    }

    @Override
    public Integer getType() {
        return QuestionTypeEnum.FILL_IN_THE_BLANK_QUESTIONS.getCode();
    }

    @Override
    public String getTypeName() {
        return QuestionTypeEnum.FILL_IN_THE_BLANK_QUESTIONS.getName();
    }

}